<template>
  <div class="users">
    <!-- 面包屑区域 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="24">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUsersList()">
            <el-button slot="append" icon="el-icon-search" @click="getUsersList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table
        :data="userlist"
        border
        stripe
        style="width: 100%">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
        <el-table-column prop="mg_state" label="状态" >
          <template v-slot="scope"><el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch></template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template v-slot="scope">
            
            <!-- 修改按钮 -->
            <el-tooltip effect="dark" content="修改" placement="top" :enterable="false" >
              <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" @click="showDeleteDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" @click="showSetDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed">
      <!-- 内容主题区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsers">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed">
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUsers">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClosed">
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="selectedRoleId" filterable placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureSetRole">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { GetUsersList, changeUserState, addUser, getEditData, editUserData, deleteUsers, getRolesList, selectedNewRole } from 'network/users'

export default {
  name: "Users",
  data() {
    // 定义添加用户表单 校验规则
    // 验证邮箱的 校验规则
    var checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9]+)/
      if(regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    // 验证手机号码的 校验规则
    var checkMobile = (rule, value, callback) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if(regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }
    
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      userlist: [],
      total: 0,

      // 需要被分配角色的用户信息
      userInfo: {},

      // 所有角色的列表
      rolesList: [],

      // 已经选中分配的角色id值
      selectedRoleId: '',

      // 控制添加用户框的显示和隐藏
      addDialogVisible: false,

      // 控制修改用户信息框的显示和隐藏
      editDialogVisible: false,

      // 控制分配角色对话框的显示和隐藏
      setRoleDialogVisible: false,

      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },

      // 需要修改的用户的原数据
      editForm: {

      },

      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名的长度在3~10个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码的长度在6~15个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },

      // 修改表单的验证规则对象
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUsersList()
  },
  methods: {
    // 获取网络请求数据
    async getUsersList() {
      const res = await GetUsersList(this.queryInfo)
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userlist = res.data.users
      this.total = res.data.total
      // console.log(res);
    },

    // 监听 pagesize 改变的事件
    handleSizeChange(newSzie) {
      this.queryInfo.pagesize = newSzie
      this.getUsersList()
    },

    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUsersList()
    },

    // 监听 switch 开关状态的改变
    async userStateChange(userinfo) {
      const res = await changeUserState(userinfo)
      if(res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },

    // 监听添加用户对话框关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },

    // 点击确定按钮, 添加新用户
    addUsers() {
      this.$refs.addFormRef.validate(async validate => {
        if(!validate) return
        // 可以发起添加用户的网络请求
        const res = await addUser(this.addForm)
        if(res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addDialogVisible = false
        // 重新刷新用户列表
        this.getUsersList()
        
      })
    },

    // 点击修改按钮, 展示用户信息
    async showEditDialog(data) {
      const res =  await getEditData(data)
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editForm = res.data
      console.log(res);
      this.editDialogVisible = true
    },

    // 确认修改用户信息
    editUsers() {
      this.$refs.editFormRef.validate(async validate => {
        if(!validate) return
        // 可以发起添加用户的网络请求
        const res = await editUserData(this.editForm)
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.editDialogVisible = false
        // 重新刷新用户列表
        this.getUsersList()
      })
    },

    // 监听修改信息框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },

    // 监听分配角色的对话框的关闭事件
    setRoleDialogClosed() {
      this.selectedRoleId = ''
    },

    // 根据id删除对应的用户信息
    showDeleteDialog(aid) {
      // 弹框询问是否删除
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteUsers(aid).then(res => {
            if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.$message.success(res.meta.msg)
            this.getUsersList()
          }).catch(err => {
            this.$message.error(err)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },

    // 展示分配用户角色对话框
    showSetDialog(userInfo) {
      this.userInfo = userInfo
      // 发起网络请求获取所有角色列表
      getRolesList().then(res => {
        if(res.meta.status !== 200 )  return this.$message.error(res.meta.msg)
        this.rolesList = res.data
        console.log(this.rolesList);
      }).catch(err => { this.$message.error(err) })

      this.setRoleDialogVisible = true
    },

    // 确认给用户添加角色
    sureSetRole() {
      if(!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色!')
      }
      selectedNewRole(this.userInfo.id, { rid: this.selectedRoleId}).then(res => {
        // console.log(res);
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.getUsersList()
      }).catch(err => { this.$message.error(err) })
      

      this.setRoleDialogVisible = false
    }
  }
}
</script>

<style>
  .el-breadcrumb {
    margin-bottom: 20px;
    font-size: 12px;
  }

  .users .el-card {
    box-shadow: 0 1px 1px rgba(0, 0, 0, .15);
  }

  .el-table {
    margin-top: 15px;
  }

  .el-pagination {
    margin-top: 15px;
  }
</style>